//
//  SimpleCode.m
//  SimpleCode
//
//  Created by mafeng on 16/8/12.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "SimpleCode.h"
#import <objc/runtime.h>
@implementation SimpleCode
+ (void)simpleCode:(Class)cls {
    // 固定字符串拼接
    NSMutableString *initHeadString = [@"// 取值,从本地获取\n- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {\n\tif (self =\n\t[super init]) {\n" mutableCopy];
    // 获取类中所有属性的名字
    unsigned int count = 0;
    NSString *initTailString = @"}\n\treturn self;\n}";
    // 获取类中属性列表
    objc_property_t *propertes = class_copyPropertyList(cls, &count);
    // 遍历列表
    for (int i = 0; i < count; i++) {
        // 获取第i个的属性
        objc_property_t property = propertes[i];
        // 获取他的属性名
        const char *propertyCString = property_getName(property);
        // 反斜杠 转义字符
        NSString *string = [NSString stringWithFormat:@"\t_%s = [aDecoder decodeObjectForKey:@\"%s\"];\n", propertyCString, propertyCString];
        // 拼接字符串
        [initHeadString appendString:string];
        
        NSLog(@"%@", string);
        NSLog(@"%d", count);
    }
    [initHeadString appendString:initTailString];
    NSLog(@"%@", initHeadString);
    // macOX程序可以获取桌面路径
    NSString *deskTopPath = [NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) firstObject];
    // 拼接路径
    NSString *file = [deskTopPath stringByAppendingPathComponent:@"Simple.m"];
    NSData *data = [initHeadString dataUsingEncoding:NSUTF8StringEncoding];
    // 写入桌面
    if ([data writeToFile:file atomically:YES]) {
        NSLog(@"❤️");
    } else {
        NSLog(@"failed");
    }
    
   
}
@end
